package com.css.fxfzfxqh.modules.buildingIndividual.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzfxqh.base.dict.service.DictService;
import com.css.fxfzfxqh.modules.buildingIndividual.entity.BuildingIndividualEntity;
import com.css.fxfzfxqh.modules.buildingIndividual.repository.BuildingIndividualRepository;
import com.css.fxfzfxqh.modules.buildingIndividual.service.BuildingIndividualService;
import com.css.fxfzfxqh.modules.buildingIndividual.verify.VerifyHandler;
import com.css.fxfzfxqh.modules.buildingIndividual.vo.ParamsVo;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.model.param.QueryByVersionParam;
import com.css.fxfzfxqh.util.CreateGson;
import com.css.fxfzfxqh.util.PlatformObjectUtils;
import com.css.fxfzfxqh.util.PlatformSessionUtils;
import com.css.fxfzfxqh.util.UUIDGenerator;
import com.css.fxfzfxqh.web.PlatformSessionContext;
import com.css.fxfzfxqh.zcpt.sys.entity.SUser;
import com.css.fxfzfxqh.zcpt.sys.entity.SysUserRole;
import com.css.fxfzfxqh.zcpt.sys.service.SUserService;
import com.css.fxfzfxqh.zcpt.sys.service.SysAreaService;
import com.css.fxfzfxqh.zcpt.sys.service.SysRoleService;
import com.css.fxfzfxqh.zcpt.sys.service.impl.SUserCacheService;
import com.css.fxfzfxqh.zcpt.sys.service.impl.SysRoleCacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class BuildingIndividualServiceImpl implements BuildingIndividualService {

    @Autowired
    BuildingIndividualRepository buildingIndividualRepository;
    @Autowired
    SysAreaService sysAreaService;
    @Autowired
    DictService dictService;
    @Autowired
    VerifyHandler verifyHandler;
    @Autowired
    SUserService sUserService;
    @Autowired
    SysRoleService sysRoleService;
    @Autowired
    SUserCacheService sUserCacheService;
    @Autowired
    SysRoleCacheService sysRoleCacheService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> upload(MultipartFile file) {
        String uploadUid = PlatformSessionContext.getUserID();
        ImportParams params = new ImportParams();
        params.setHeadRows(3);
        params.setVerifyHandler(verifyHandler);
        params.setNeedVerify(true);
        boolean res = false;
        Map<String, Object> map = new HashMap<>();
        try {
            InputStream inputStream = file.getInputStream();
            ExcelImportResult<BuildingIndividualEntity> result = ExcelImportUtil.importExcelMore(inputStream, BuildingIndividualEntity.class, params);
            List<BuildingIndividualEntity> failList = result.getFailList();
            if (PlatformObjectUtils.isNotEmpty(failList)) {
                StringBuilder errorMsg = new StringBuilder("<font size='4px' color='red'>导入失败,请修改后重新导入</font><br>");
                errorMsg.append("<font size='4px' color='red'>导入失败原因:</font>");
                for (BuildingIndividualEntity buildingIndividualEntity : failList) {
                    errorMsg.append("<font size='4px' ><br>").append("第").append(buildingIndividualEntity.getRowNum() + 1).append("行： ").append(buildingIndividualEntity.getErrorMsg()).append("</font><br>");
                }
                map.put("res", res);
                map.put("mess", errorMsg);
                return map;
            }
            SUser sUser = sUserCacheService.getSUser(uploadUid);
            if (sUser == null) {
                throw new RuntimeException("用户信息查询失败!");
            }
            String userMaxRole = getUserMaxRole(uploadUid);
            StringBuilder userProvinceErrorMsg = new StringBuilder("<font size='4px' color='red'>导入失败,请修改后重新导入</font><br>");
            userProvinceErrorMsg.append("<font size='4px' color='red'>导入失败原因:</font>");
            boolean resFlag = true;
            List<BuildingIndividualEntity> resultData = result.getList();//解析excel
            if (PlatformObjectUtils.isNotEmpty(resultData)) {
                List<BuildingIndividualEntity> list = new ArrayList<>();
                for (BuildingIndividualEntity buildingIndividualEntity : resultData) {
                    buildingIndividualEntity.setId(UUIDGenerator.getUUID());
                    String province = buildingIndividualEntity.getProvince();
                    String city = buildingIndividualEntity.getCity();
                    String county = buildingIndividualEntity.getCounty();
                    String divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(province, "UTF-8"), URLEncoder.encode(city, "UTF-8"), URLEncoder.encode(county, "UTF-8"));
                    buildingIndividualEntity.setProvinceId(divisionIds.split("_")[0]);
                    buildingIndividualEntity.setCityId(divisionIds.split("_")[1]);
                    buildingIndividualEntity.setCountyId(divisionIds.split("_")[2]);
                    if (PlatformObjectUtils.isNotEmpty(userMaxRole)&&!userMaxRole.equals("qh_gj_role")) {
                        if (userMaxRole.equals("qh_province_role") && !sUser.getProvinceId().equals(buildingIndividualEntity.getProvinceId())) {
                            resFlag = false;
                            userProvinceErrorMsg.append("<font size='4px' ><br>").append("第").append(buildingIndividualEntity.getRowNum() + 1).append("行").append("的数据省份不是用户所在省份").append("</font><br>");
                            continue;
                        } else if (userMaxRole.equals("qh_city_role") && !sUser.getCityId().equals(buildingIndividualEntity.getCityId())) {
                            resFlag = false;
                            userProvinceErrorMsg.append("<font size='4px' ><br>").append("第").append(buildingIndividualEntity.getRowNum() + 1).append("行").append("的数据省份不是用户所在地级市").append("</font><br>");
                            continue;
                        } else if (userMaxRole.equals("ph_county_role") && !sUser.getCountyId().equals(buildingIndividualEntity.getCountyId())) {
                            resFlag = false;
                            userProvinceErrorMsg.append("<font size='4px' ><br>").append("第").append(buildingIndividualEntity.getRowNum() + 1).append("行").append("的数据省份不是用户所在区县").append("</font><br>");
                            continue;
                        }
                        buildingIndividualEntity.setIsCountryLevel(0);
                    } else {
                        buildingIndividualEntity.setIsCountryLevel(1);
                    }
                    if (!resFlag) {
                        continue;
                    }
                    //设防情况
                    buildingIndividualEntity.setDefenceLevel(dictService.getKeyByDictCodeAndValue("sfqk", buildingIndividualEntity.getDefenceLevel()));
                    //结构类型一级
                    String structureType1 = buildingIndividualEntity.getStructureType1();
                    buildingIndividualEntity.setStructureType1(dictService.getKeyByDictCodeAndValue("jglxyj", structureType1));
                    if (structureType1.equals("砌体结构")) {
                        buildingIndividualEntity.setStructureType2(dictService.getKeyByDictCodeAndValue("qtjgej", buildingIndividualEntity.getStructureType2()));
                    }
                    if (structureType1.equals("钢筋混凝土结构")) {
                        buildingIndividualEntity.setStructureType2(dictService.getKeyByDictCodeAndValue("gjhntjgej", buildingIndividualEntity.getStructureType2()));
                    }
                    if (structureType1.equals("工业厂房")) {
                        buildingIndividualEntity.setStructureType2(dictService.getKeyByDictCodeAndValue("gycfej", buildingIndividualEntity.getStructureType2()));
                    }
                    String usage1 = buildingIndividualEntity.getUsage1();//房屋类型一级
                    buildingIndividualEntity.setUsage1(dictService.getKeyByDictCodeAndValue("fwytyj", usage1));
                    if (usage1.equals("第Ⅰ类")) {
                        buildingIndividualEntity.setUsage2(dictService.getKeyByDictCodeAndValue("dylej", buildingIndividualEntity.getUsage2()));
                    }
                    if (usage1.equals("第Ⅱ类")) {
                        buildingIndividualEntity.setUsage2(dictService.getKeyByDictCodeAndValue("delej", buildingIndividualEntity.getUsage2()));
                    }
                    if (usage1.equals("第Ⅲ类")) {
                        buildingIndividualEntity.setUsage2(dictService.getKeyByDictCodeAndValue("fwytsan", buildingIndividualEntity.getStructureType2()));
                    }
                    buildingIndividualEntity.setYear(dictService.getKeyByDictCodeAndValue("year", buildingIndividualEntity.getYear()));
                    buildingIndividualEntity.setFloors(dictService.getKeyByDictCodeAndValue("cengshu", buildingIndividualEntity.getFloors()));
                    buildingIndividualEntity.setDelFlag("0");
                    buildingIndividualEntity.setCreateUser(uploadUid);
                    buildingIndividualEntity.setCreateName(sUser.getUserName());
                    buildingIndividualEntity.setCreateTime(new Date());
                    buildingIndividualEntity.setGeom("POINT(" + buildingIndividualEntity.getLongitude() + " " + buildingIndividualEntity.getLatitude() + ")");
                    list.add(buildingIndividualEntity);
                }
                if (!resFlag) {
                    map.put("res", false);
                    map.put("mess", userProvinceErrorMsg);
                    return map;
                }
                for (BuildingIndividualEntity buildingIndividualEntity : list) {
                    List<BuildingIndividualEntity> tList = buildingIndividualRepository.findByOnlyOneCondition(buildingIndividualEntity);
                    for (BuildingIndividualEntity individualEntity : tList) {
                        buildingIndividualRepository.delete(individualEntity.getId());
                    }
                    res = buildingIndividualRepository.save(buildingIndividualEntity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("res", res);
        return map;
    }

    private String getUserMaxRole(String uploadUid) {
        List<SysUserRole> roleList = sysRoleCacheService.getRole(uploadUid);
        if (roleList == null) {
            throw new RuntimeException("未查询到用户角色信息!");
        }
        List<String> roleCodeList = roleList.stream().map(r -> r.getRoleCode()).collect(Collectors.toList());
        if (roleCodeList.contains("qh_gj_role") || roleCodeList.contains("fxqh_test_role")) {
            return "qh_gj_role";
        }
        if (roleCodeList.contains("qh_province_role")) {
            return "qh_province_role";
        }
        if (roleCodeList.contains("qh_city_role")) {
            return "qh_city_role";
        }
        if (roleCodeList.contains("ph_county_role")) {
            return "ph_county_role";
        }
        return null;
    }

    @Override
    public Map<String, Object> page(ParamsVo paramsVo, int curPage, int pageSize) {
//        String userId = PlatformSessionContext.getUserID();
//        String user = sUserService.getSUser(userId);
//        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
//        String role = sysRoleService.getRoleByUserId(userId);
//        //当前登录人所有的角色
//        StringBuilder roles = new StringBuilder();
//        List<Map> maps = JSONObject.parseArray(role, Map.class);//一个人可能有多个角色
//        for (int i = 0; i < maps.size(); i++) {
//            Map map = maps.get(i);
//            roles.append(map.get("roleCode") + ",");
//        }
//        String allRole = roles.toString();
//        String provinceId = sUser.getProvinceId();//省id
//        Map<String, Object> map = buildingIndividualRepository.page(paramsVo, curPage, pageSize, allRole, provinceId);
        Map<String, Object> map = buildingIndividualRepository.page(paramsVo, curPage, pageSize);
        return map;
    }

    @Override
    public Map<String, Object> getVersion(ParamsVo paramsVo, int curPage, int pageSize) {
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        //当前登录人所有的角色
        StringBuilder roles = new StringBuilder();
        List<Map> maps = JSONObject.parseArray(role, Map.class);//一个人可能有多个角色
        for (int i = 0; i < maps.size(); i++) {
            Map map = maps.get(i);
            roles.append(map.get("roleCode") + ",");
        }
        String allRole = roles.toString();
        String provinceId = sUser.getProvinceId();//省id
        Map<String, Object> map = buildingIndividualRepository.getVersion(paramsVo, curPage, pageSize, allRole, provinceId);
        return map;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean update(BuildingIndividualEntity buildingIndividualEntity) throws UnsupportedEncodingException {
        String province = buildingIndividualEntity.getProvince();
        String city = buildingIndividualEntity.getCity();
        String county = buildingIndividualEntity.getCounty();
        String divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(province, "UTF-8"), URLEncoder.encode(city, "UTF-8"), URLEncoder.encode(county, "UTF-8"));
        buildingIndividualEntity.setProvinceId(divisionIds.split("_")[0]);
        buildingIndividualEntity.setCityId(divisionIds.split("_")[1]);
        buildingIndividualEntity.setCountyId(divisionIds.split("_")[2]);

        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        buildingIndividualEntity.setUpdateUser(userId);
        buildingIndividualEntity.setUpdateName(sUser.getUserName());
        buildingIndividualEntity.setUpdateTime(new Date());
        return buildingIndividualRepository.update(buildingIndividualEntity);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean delete(String ids) {
        boolean res = false;
        for (String id : ids.split(",")) {
            res = buildingIndividualRepository.delete(id);
        }
        return res;
    }

    @Override
    public BuildingIndividualEntity findById(String id) {
        return buildingIndividualRepository.findById(id);
    }

    @Override
    public Map<String, String> getRole() {
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        //当前登录人所有的角色
        StringBuilder roles = new StringBuilder();
        List<Map> maps = JSONObject.parseArray(role, Map.class);//一个人可能有多个角色
        for (int i = 0; i < maps.size(); i++) {
            Map map = maps.get(i);
            roles.append(map.get("roleCode") + ",");
        }
        String allRole = roles.toString();
        Map<String, String> map = new HashMap<>();
        String r = "";
//        if(allRole.contains(FxfzConstants.YPG_COUN_GL_ROLE) || allRole.contains(FxfzConstants.YPG_COUN_YW_ROLE)){
//            r = "COUN";
//        } else if(allRole.contains(FxfzConstants.YPG_PRI_GL_ROLE) || allRole.contains(FxfzConstants.YPG_PRI_YW_ROLE)){//省级
//            r = "PRI";
//            map.put("provinceId",sUser.getProvinceId());
//        }
        map.put("role", r);
        return map;
    }

    @Override
    public List<BuildingIndividualEntity> queryYwData(QueryByVersionParam queryByVersionParam) {
        return buildingIndividualRepository.queryYwData(queryByVersionParam);
    }

    @Override
    public List<BuildingIndividualEntity> queryDataByParam1(QueryByVersionParam queryByVersionParam) {
        return buildingIndividualRepository.queryDataByParam1(queryByVersionParam);
    }

    @Override
    public Map<String, Object> queryBuildingMap(ParamsVo paramsVo) {
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        //当前登录人所有的角色
        StringBuilder roles = new StringBuilder();
        List<Map> maps = JSONObject.parseArray(role, Map.class);//一个人可能有多个角色
        for (int i = 0; i < maps.size(); i++) {
            Map map = maps.get(i);
            roles.append(map.get("roleCode") + ",");
        }
        String allRole = roles.toString();
        String provinceId = sUser.getProvinceId();//省id
        Map<String, Object> map = buildingIndividualRepository.queryBuildingMap(paramsVo, allRole, provinceId);
        return map;
    }
}
